/* *****************************************************************************************************
 * Copyright 2009. Dbwebx Group
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 * *****************************************************************************************************
 */
package org.dbwebx.service.dao.impl.base;

import org.dozer.Mapper;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * The base service implementation. Contains generic methods and fields.
 * 
 * @author Izzet_Mustafayev
 * @param <E>
 * 
 */
public class BaseService<T, E> {
	/**
	 * Spring managed JPA {@link EntityManager} reference.
	 */
	@PersistenceContext
	protected EntityManager em;

	/**
	 * Dozer Mapper reference.
	 */
	@Autowired
	protected Mapper dozerMapper;

	/**
	 * Base list mapper. Maps input list of the specific type.
	 * 
	 * @param list
	 *            the object list to map from
	 * @param targetClazz
	 *            the target bean to map to
	 * @return mapped list
	 */
	protected List<T> mapList(final List<E> list, final Class<T> targetClazz) {
		List<T> resultList = new ArrayList<T>();

		if (!list.isEmpty()) {
			for (E mappableBean : list) {
				resultList.add(dozerMapper.map(mappableBean, targetClazz));
			}
		}

		return resultList;
	}

	/**
	 * Maps {@link List} for a specific <a
	 * href="http://dozer.sourceforge.net/documentation/contextmapping.html"
	 * >context</a>.
	 * 
	 * @param list
	 *            the {@link List} to map
	 * @param targetClazz
	 *            the target maping object
	 * @param caseId
	 * @return
	 */
	protected List<T> mapList(final List<E> list, final Class<T> targetClazz,
			final String caseId) {
		List<T> resultList = new ArrayList<T>();

		if (!list.isEmpty()) {
			for (E mappableBean : list) {
				resultList.add(dozerMapper.map(mappableBean, targetClazz,
						caseId));
			}
		}

		return resultList;
	}

	protected T map(E ino, Class<T> targetClazz) {
		T result = null;

		if (null != ino) {
			result = dozerMapper.map(ino, targetClazz);
		}

		return result;
	}

	protected T map(final E ino, final Class<T> targetClazz, final String caseId) {
		T result = null;

		if (null != ino) {
			result = dozerMapper.map(ino, targetClazz, caseId);
		}

		return result;
	}
}
